#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<vector>
#include"Thread.hpp"
#define NUM 4
using namespace ThreadModel;

static int g_ticket = 10000;
struct ThreadData
{
    std::string name;
    pthread_mutex_t* lock;
};


void BuyTicket(ThreadData& td)
{
    while(true)
    {
        pthread_mutex_lock(td.lock);
        if(g_ticket > 0)
        {
            usleep(1000);
            printf("%s buy ticket:%d\n",td.name.c_str(),g_ticket);
            g_ticket--;
            pthread_mutex_unlock(td.lock);
        }
        else
        {
            pthread_mutex_unlock(td.lock);
            break;
        }
    }
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);

    //只需传递一个模板参数，
    std::vector<MyThread<ThreadData>> threads;
    for(int i = 0; i < NUM; i++)
    {
        ThreadData* td = new ThreadData();
        td->lock = &mutex;
        threads.emplace_back(BuyTicket,*td);
        td->name = threads.back().name();
    }

    for(int i = 0; i < NUM; i++)
    {
        threads[i].create();
    }

    for(int i = 0; i < NUM; i++)
    {
        threads[i].join();
    }
    return 0;
}



// static int g_ticket = 10000;
// pthread_mutex_t lock;//设置全局的锁

// void* BuyTicket(void* args)
// {
//     const char* name = (const char*)args;
//     while(true)
//     {
//         pthread_mutex_lock(&lock);//加锁
//         if(g_ticket > 0)
//         {
//             usleep(1000);
//             printf("%s buy ticket:%d\n",name,g_ticket);
//             g_ticket--;
//             pthread_mutex_unlock(&lock);//解锁
//         }
//         else
//         {
//             pthread_mutex_unlock(&lock);//解锁
//             break;
//         }
//     }
//     return nullptr;
// }

// int main()
// {
//     //1. 静态分配
//     // lock = PTHREAD_MUTEX_INITIALIZER;
//     //2. 动态分配
//     pthread_mutex_init(&lock,nullptr);
    
//     //锁的销毁

//     pthread_t tid1,tid2,tid3,tid4;
//     pthread_create(&tid1,nullptr,BuyTicket,(void*)"pthread-1");
//     pthread_create(&tid2,nullptr,BuyTicket,(void*)"pthread-2");
//     pthread_create(&tid3,nullptr,BuyTicket,(void*)"pthread-3");
//     pthread_create(&tid4,nullptr,BuyTicket,(void*)"pthread-4");

//     pthread_join(tid1,nullptr);
//     pthread_join(tid2,nullptr);
//     pthread_join(tid3,nullptr);
//     pthread_join(tid4,nullptr);
//     pthread_mutex_destroy(&lock);


//     return 0;
// }